<script setup>
import { useUserStore } from "@/store/user";
import { useAppStore } from "@/store/app";
import { storeToRefs } from "pinia";
import { ref, computed } from "vue";

const userStore = useUserStore();
const appStore = useAppStore();
console.log(appStore.config);
console.log(userStore);
console.log(userStore.name);
const name = computed(() => userStore.name);
const { age } = storeToRefs(userStore);

const updateUserState = () => {
  const { name, age } = userStore.$state;
  userStore.updateState({
    name: name + 1,
    age: age + 1,
  });
};
const active = ref(1);
const onChange = (index) => {
  // console.log("🚀 ~ file: function.vue:24 ~ index", index);
};

const videoInputList = ref([]);
const videoDeviceId = ref("");

const handleClick = () => {
  // console.log("🚀 ~ file: function.vue:28 ~ handleClick", window.navigator);
  getDevices();
};

const chooseDevice = (index) => {
  videoDeviceId.value = videoInputList.value[index].deviceId;
  let mediaStream = navigator.mediaDevices.getUserMedia({
    video: {
      deviceId: videoDeviceId.value,
    },
  });
  mediaStream.then((stream) => {
    console.log(
      "🚀 ~ file: function.vue:43 ~ mediaStream.then ~ stream",
      stream
    );
    let video = document.getElementById("video");
    video.srcObject = stream;
    video.play();
  });
};

const getDevices = () => {
  /*
    1. 首次允许需要引导用户 浏览器获取摄像头权限
  */
  //首次运行引导用户，信任域名
  let oneVideo = window.localStorage.getItem("oneVideo");
  if (oneVideo == null) {
    if (
      navigator.mediaDevices.getUserMedia ||
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia
    ) {
      //调用用户媒体设备, 访问摄像头
      getUserMedia({ video: { width: 480, height: 320 } }, success, error);
    } else {
      alert("不支持访问用户媒体");
    }
  }
  if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
    console.log("enumerateDevices is not supported!");
  } else {
    // 获取本机媒体设备 window对象
    navigator.mediaDevices.enumerateDevices().then(function (devices) {
      devices.forEach(function (device) {
        if (device.kind === "videoinput") {
          videoInputList.value.push(device);
        }
        console.log(`${device.kind}:${device.label} id = ${device.deviceId}`);
      });
    });
  }
};
function success(stream) {
  console.log(stream);
  window.localStorage.setItem("oneVideo", "false");
  window.location.reload();
}
function error(error) {
  console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
}
//访问用户媒体设备的兼容方法
function getUserMedia(constraints, success, error) {
  if (navigator.mediaDevices.getUserMedia) {
    //最新的标准API
    navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
  } else if (navigator.webkitGetUserMedia) {
    //webkit核心浏览器
    navigator.webkitGetUserMedia(constraints, success, error);
  } else if (navigator.mozGetUserMedia) {
    //firfox浏览器
    navigator.mozGetUserMedia(constraints, success, error);
  } else if (navigator.getUserMedia) {
    //旧版API
    navigator.getUserMedia(constraints, success, error);
  }
}
</script>
<template>
  <div class="function-class">
    <div class="sidebar-tab">
      <van-config-provider theme="dark">
        <van-sidebar v-model="active" @change="onChange">
          <van-sidebar-item title="Pinia" />
          <van-sidebar-item title="webRtc" />
          <van-sidebar-item title="more" disabled />
        </van-sidebar>
      </van-config-provider>
    </div>

    <div class="sidebar-content">
      <div v-if="active === 0">
        <van-space direction="vertical" fill>
          <div>姓名：{{ name }}</div>
          <div>年龄：{{ age }}</div>
          <div>计算的名字：{{ userStore.fullName }}</div>
          <div>app的config: {{ appStore.config }}</div>
        </van-space>

        <van-divider
          :style="{
            color: '#1989fa',
            borderColor: '#1989fa',
          }"
        />
        <van-button plain type="success" @click="updateUserState">
          更新数据
        </van-button>
      </div>
      <div v-if="active === 1">
        <h1>webRtc</h1>
        <h2>音视频接入</h2>
        <div class="fetch-device">
          <van-button plain type="warning" @click="handleClick"
            >获取设备</van-button
          >
        </div>
        <div class="device-list">
          <van-button
            plain
            hairline
            type="primary"
            v-for="(item, index) in videoInputList"
            :key="index"
            @click="chooseDevice(index)"
            >设备:{{ item.label + "_" + index }}</van-button
          >
        </div>
        <div class="video-class">
          <video id="video" src=""></video>
        </div>
      </div>
      <div v-if="active === 2">
        <h1>more</h1>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.function-class {
  display: flex;
  .sidebar-content {
    // padding-top: 10px;
    padding: 10px;
    width: 100%;
  }
  #video {
    width: 100%;
    height: 120px;
  }
  .fetch-device {
    margin-bottom: 10px;
  }
  .device-list {
    display: flex;
    // flex-direction: column;
    gap: 10px;
  }
  .video-class {
    margin-top: 20px;
    width: 85%;
    height: 120px;
    border: 1px solid green;
    border-radius: 4px;
  }
}
</style>
